﻿using System;
using Audio;
using UnityEngine;
using PrimeTween;

namespace Combat
{
    [RequireComponent(typeof(Health))]
    public class ExplodeOnDied : MonoBehaviour
    {
        public static event Action AnyThingExploded;
        
        [SerializeField] private ParticleSystem explosionEffect;
        [SerializeField] private AudioClip explosionSound;
        [SerializeField] private SpriteRenderer spriteRenderer;
        private Health _health;
        
        private Tween _tween;


        private void Awake()
        {
            _health = GetComponent<Health>();
            
            _health.Died += Health_Died;
        }

        private void OnDestroy()
        {
            _tween.Stop();
        }

        private void Health_Died()
        {
            AudioPlayer.Instance.PlaySound(explosionSound);
            
            spriteRenderer.enabled = false;
            explosionEffect.Play();
            AnyThingExploded?.Invoke();

            _tween = Tween.Delay(1f, DestroySelf);
        }

        private void DestroySelf()
        {
            Destroy(gameObject);
        }
    }
}